import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Message } from './entities/message.entity';
import { CacheService } from '../cache/cache.service';

export interface MessageQueryParams {
  current?: number;
  pageSize?: number;
  imei?: string;
  deviceAddress?: string;
  dataType?: string;
  reportType?: string;
  startTime?: string;
  endTime?: string;
}

export interface MessageListResponse {
  data: Message[];
  total: number;
  success: boolean;
}

@Injectable()
export class MessageService {
  constructor(
    @InjectRepository(Message)
    private readonly messageRepository: Repository<Message>,
    private readonly cacheService: CacheService,
  ) {}

  // 将 Date 对象转换为数据库格式的字符串
  public formatTimestamp(timestamp: Date | string): string {
    const date = new Date(timestamp);
    // 转为东八区时间
    date.setHours(date.getHours() + 8);
    const year = date.getUTCFullYear();
    const month = String(date.getUTCMonth() + 1).padStart(2, '0');
    const day = String(date.getUTCDate()).padStart(2, '0');
    const hours = String(date.getUTCHours()).padStart(2, '0');
    const minutes = String(date.getUTCMinutes()).padStart(2, '0');
    const seconds = String(date.getUTCSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  create(message: Partial<Message>) {
    if (message.parsedData && typeof message.parsedData !== 'string') {
      message.parsedData = JSON.stringify(message.parsedData);
    }
    return this.messageRepository.save(message);
  }

  async findAll(params: MessageQueryParams = {}): Promise<MessageListResponse> {
    const {
      current = 1,
      pageSize = 10,
      imei,
      deviceAddress,
      dataType,
      reportType,
      startTime,
      endTime,
    } = params;

    const queryBuilder = this.messageRepository.createQueryBuilder('message');

    // 添加搜索条件
    if (imei) {
      queryBuilder.andWhere('message.imei LIKE :imei', { imei: `%${imei}%` });
    }
    if (deviceAddress) {
      queryBuilder.andWhere('message.deviceAddress LIKE :deviceAddress', {
        deviceAddress: `%${deviceAddress}%`,
      });
    }
    if (dataType) {
      queryBuilder.andWhere('message.dataType LIKE :dataType', {
        dataType: `%${dataType}%`,
      });
    }
    if (reportType) {
      queryBuilder.andWhere('message.reportType LIKE :reportType', {
        reportType: `%${reportType}%`,
      });
    }
    if (startTime && endTime) {
      queryBuilder.andWhere(
        'message.timestamp BETWEEN :startTime AND :endTime',
        {
          startTime: startTime,
          endTime: endTime,
        },
      );
    }

    // 添加排序
    queryBuilder.orderBy('message.createdAt', 'DESC');

    // 获取总数
    const total = await queryBuilder.getCount();

    // 分页
    const skip = (current - 1) * pageSize;
    queryBuilder.skip(skip).take(pageSize);

    const data = await queryBuilder.getMany();

    return {
      data,
      total,
      success: true,
    };
  }

  async findOne(id: number): Promise<Message | null> {
    try {
      console.log(`Looking for message with ID: ${id}`);
      const message = await this.messageRepository.findOne({
        where: { id },
      });
      console.log(`Found message:`, message);
      return message;
    } catch (error) {
      console.error(`Error finding message with ID ${id}:`, error);
      throw error;
    }
  }

  update(id: number, update: Partial<Message>) {
    return this.messageRepository.update(id, update);
  }

  remove(id: number) {
    return this.messageRepository.delete(id);
  }

  // 通用方法：获取原始消息数据
  async getRawMessages(reportType?: string, startDate?: string, endDate?: string) {
    const queryBuilder = this.messageRepository.createQueryBuilder('message');

    // 根据reportType过滤
    if (reportType) {
      queryBuilder.where('message.reportType = :reportType', { reportType });
    }

    // 添加日期范围过滤
    if (startDate && endDate) {
      const startDateTime = startDate + ' 00:00:00';
      const endDateTime = endDate + ' 23:59:59';
      queryBuilder.andWhere(
        'message.timestamp BETWEEN :startDate AND :endDate',
        { startDate: startDateTime, endDate: endDateTime },
      );
    }

    // 选择需要的字段
    queryBuilder.select([
      'message.deviceAddress',
      'message.timestamp',
      'message.parsedData',
    ]);

    // 按时间排序
    queryBuilder.orderBy('message.timestamp', 'ASC');

    const messages = await queryBuilder.getMany();

    return {
      success: true,
      data: messages,
    };
  }

  async getTemperatureStats(startDate?: string, endDate?: string) {
    const cacheKey = this.cacheService.generateCacheKey('temperature_stats', {
      startDate,
      endDate,
    });
    
    return this.cacheService.getOrSet(
      cacheKey,
      () => this.getRawMessages('01', startDate, endDate),
      300, // 缓存5分钟
    );
  }

  async getCableTemperatureStats(startDate?: string, endDate?: string) {
    const cacheKey = this.cacheService.generateCacheKey('cable_temperature_stats', {
      startDate,
      endDate,
    });
    
    return this.cacheService.getOrSet(
      cacheKey,
      () => this.getRawMessages('02', startDate, endDate),
      300, // 缓存5分钟
    );
  }

  async getDischargeMaxStats(startDate?: string, endDate?: string) {
    const cacheKey = this.cacheService.generateCacheKey('discharge_max_stats', {
      startDate,
      endDate,
    });
    
    return this.cacheService.getOrSet(
      cacheKey,
      () => this.getRawMessages('02', startDate, endDate),
      300, // 缓存5分钟
    );
  }

  async getWaterLeakStats(startDate?: string, endDate?: string) {
    const cacheKey = this.cacheService.generateCacheKey('water_leak_stats', {
      startDate,
      endDate,
    });
    
    return this.cacheService.getOrSet(
      cacheKey,
      () => this.getRawMessages('01', startDate, endDate),
      300, // 缓存5分钟
    );
  }
}
